package com.forekonw.demo1;

import com.forekonw.demo.Employee;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 预处理 PreparedStatement
 */
public class PreparedStatementDemo {
    public static void main(String[] args) {
        Connection conn = null;
        ResultSet rs = null;
        PreparedStatement ps  = null;
                String fn = "com.mysql.jdbc.Driver";
        try {
            Class.forName(fn);
            String url = "jdbc:mysql://localhost:3306/aaa?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
            String user = "root";
            String password = "root";
            conn = DriverManager.getConnection(url,user,password);
            ps  = conn.prepareStatement("select * from employee where username=? and password =?");
//            int a = stat.executeUpdate("insert into employee(username,password)values ('tom','15612')");
//            System.out.println(a);
            ps.setString(1,"fender");
            ps.setString(2,"123456");
            rs = ps.executeQuery();
            List<Employee> list = new ArrayList<>();
            while (rs.next()){
                int id = rs.getInt("id");
                String username = rs.getString("username");
                String pass = rs.getString("password");
                Employee employee = new Employee();
                employee.setId(id);
                employee.setUsername(username);
                employee.setPassword(pass);
                list.add(employee);
            }
            for (Employee e :list) {
                System.out.println(e.getId()+"---"+e.getUsername()+"---"+e.getPassword());
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
